package com.agritech.environment;

import com.agritech.observer.EnvironmentObserver;
import com.agritech.observer.EnvironmentSubject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 环境监测系统
 * 观察者模式中的具体主题（被观察者），负责收集环境数据并通知观察者
 */
public class EnvironmentMonitoringSystem implements EnvironmentSubject {
    private final List<EnvironmentObserver> observers;
    private final EnvironmentData environmentData;
    private final Random random;
    
    public EnvironmentMonitoringSystem() {
        this.observers = new ArrayList<>();
        this.environmentData = new EnvironmentData();
        this.random = new Random();
        this.environmentData.setDataSource("农田传感器网络");
    }
    
    @Override
    public void registerObserver(EnvironmentObserver observer) {
        if (!observers.contains(observer)) {
            observers.add(observer);
            System.out.println("新的观察者已注册到环境监测系统");
        }
    }
    
    @Override
    public void removeObserver(EnvironmentObserver observer) {
        observers.remove(observer);
        System.out.println("观察者已从环境监测系统移除");
    }
    
    @Override
    public void notifyObservers() {
        for (EnvironmentObserver observer : observers) {
            observer.update(environmentData);
        }
    }
    
    /**
     * 模拟从传感器收集环境数据
     */
    public void collectData() {
        // 模拟收集数据
        environmentData.setSoilMoisture(random.nextDouble() * 100);
        environmentData.setSoilPH(4.0 + random.nextDouble() * 4.0); // pH 4-8
        environmentData.setSoilNutrient(random.nextDouble() * 100);
        environmentData.setTemperature(10.0 + random.nextDouble() * 30.0); // 10-40°C
        environmentData.setHumidity(random.nextDouble() * 100);
        environmentData.setWindSpeed(random.nextDouble() * 10.0); // 0-10 m/s
        
        // 根据土壤湿度设置作物状态
        double moisture = environmentData.getSoilMoisture();
        if (moisture < 30) {
            environmentData.setCropStatus("缺水");
        } else if (moisture > 80) {
            environmentData.setCropStatus("过湿");
        } else {
            environmentData.setCropStatus("良好");
        }
        
        environmentData.setTimestamp(System.currentTimeMillis());
        
        System.out.println("环境数据已收集完成");
        System.out.println(environmentData);
        
        // 通知所有观察者
        notifyObservers();
    }
    
    /**
     * 获取当前环境数据
     * @return 环境数据对象
     */
    public EnvironmentData getEnvironmentData() {
        return environmentData;
    }
}